export const addCirPicture = (editor) => {

    const {Components} = editor;

    Components.addType('addCirPicture', {
      model: {
        defaults: {
          name: 'addCirPicture',
          droppable: false,
          attributes: {
              title:'注意：最好拟定需要的轮播图片数量，克隆图片最好以原定的前三张图片为原件克隆，\n否则可能出现克隆后的图片失去监听，另外图片设置范围为2~6张，最好不要克隆太多\n然后删掉太多，在删除过程中可能会出现性能卡顿！',
              timer:1,
              width:'500',
              height:'400',
              cirTime:5000,//5s
              class:'cirpdefault'
          },
          traits:[
            {  
              type: 'text',  
              label: '标题',  
              name: 'title',  
              default: 'Untitled' // 这里设置了默认值为'Untitled'  
            },  
            {  
              type: 'text',  
              label: 'id',  
              name: 'id'
            },   
            {
              type: 'number',
              label: '高',
              changeProp:1,
              name: 'height',
              default: '400px',
            },  
            {
              type: 'number',
              label: '宽',
              changeProp:1,
              name: 'width',
              default: '500px',
            },
            {
              type: 'number',
              name: 'cirTime',
              label:'轮播时间',
              changeProp:1,
              default: '5000',
            },
          ],
          components: [{
            type: 'div',
            attributes: {
                class: 'carousel'
            },
            components: [{
                type: 'div',
                attributes: {
                    class: 'carousel-images'
                },
                components: [{
                  type: 'image',
                  attributes: {
                      src:'https://gcu-ht.gcu.edu.cn/_upload/tpl/04/c3/1219/template1219/summary.jpg' ,alt:'Image 1'
                  },
                },
                {
                  type: 'image',
                  attributes: {
                      src:'https://gcu-ht.gcu.edu.cn/_upload/tpl/04/c3/1219/template1219/summary.jpg', alt:'Image 1'
                  },
                },
                {
                  type: 'image',
                  attributes: {
                      src:'https://gcu-ht.gcu.edu.cn/_upload/tpl/04/c3/1219/template1219/summary.jpg', alt:'Image 1'
                  },
                }
              ]
              },
              {
                type:'div',
                attributes:{
                  class: 'carousel-bottom'
                },
              },
              {
                tagName:'button',
                type: 'button',
                attributes: {
                    class:'carousel-prev'
                },
                content:'<'
              },{
                tagName:'button',
                type: 'button',
                attributes: {
                    class:'carousel-next'
                },
                content:'>'
              }

            ]
          }
        ],
        styles:`
        .cirpdefault{width:500px;height:400px;}
        .carousel { 
          position: relative;  
          width: 100%;  
          height: 100%;  
          overflow: hidden; }  
          .carousel-images {  
          display: flex;
          justify-content: space-between;
          transition: transform 0.8s ease-in-out;  
        }  
         .carousel-bottom{
          position: absolute;
          z-index: 10;
          width: 100%;height: 18%;background-color: gray;
          filter: opacity(0.7);
          display: flex;
          align-items: center;
          justify-content: left;
          overflow-y:hidden;
          scrollbar-width: none;
          left: 0;
          bottom: 0;
          transition: 0.5s;
        }
        .carousel-bottom:hover{
          filter: opacity(0.9);
        }
        .carousel-bottom img{
          border: 1px solid black;
          border-radius: 5px;
          height: 80%;
          margin: 0 3%;
        }
        .carousel-bottom img:hover{
          border: 1px solid white;
        }
          .carousel-images img { 
            min-width:100%;
            max-width:100%;
            height:400px;
          }  
        .carousel-prev{
          position: absolute;  
          filter: opacity(0);
          transition: 1s;
          top: 50%;  
          transform: translateY(-50%); background-color: rgba(0, 0, 0, 0.5);  
          color: #fff;  
          border: none; padding: 10px;  
          cursor: pointer; 
          left: 10px;
        }
        .carousel-next { 
          position: absolute;  
          filter: opacity(0);
          transition: 1s;
          top: 50%;  
          transform: translateY(-50%); background-color: rgba(0, 0, 0, 0.5);  
          color: #fff;  
          border: none; padding: 10px;  
          cursor: pointer;  
          right: 10px;
        }  
        .carousel:hover .carousel-prev{ filter: opacity(1);
        }  
        .carousel:hover .carousel-next{filter: opacity(1);}  
        `,
          script() {
            window.clearInterval(sessionStorage.getItem(this.attributes.id.value))
            var thx = document.getElementById(this.attributes.id.value);
            thx.style.width = `${this.attributes.width.value}px`;
            thx.style.height = `${this.attributes.height.value}px`;
            const carouselImages = thx.getElementsByClassName("carousel-images")[0];
            const carouselImagesItem = carouselImages.getElementsByTagName('img');
            const carouselPrevButton = thx.querySelector(".carousel-prev");
            const carouselNextButton = thx.querySelector(".carousel-next");
            let carouselBottom = thx.querySelector(".carousel-bottom"); 
            let currentIndex = 0;  
            let poin = false;
            const imagesCount = carouselImagesItem.length; 
            carouselBottom.innerHTML = '';
            let that = this;
            for(let i = 0;i<imagesCount;i++){
              let node = document.createElement('img');
              node.src = carouselImagesItem[i].src;
              node.alt = carouselImagesItem[i].alt;
              carouselImagesItem[i].style.height = `${that.attributes.height.value}px`
              carouselBottom.appendChild(node);
              node.onmouseover = () =>{
                poin = true;
                currentIndex = i;
                switchImage(currentIndex);
              }
              // 添加图片切换监听
              var observer = new MutationObserver((changes) => {
                changes.forEach(change => {
                    if(change.attributeName.includes('src')){
                      carouselBottomItem[i].src = carouselImagesItem[i].src;
                    }
                });
              });
              observer.observe(carouselImagesItem[i], {attributes : true});
            }
            let carouselBottomItem = carouselBottom.getElementsByTagName('img');
            carouselBottomItem[currentIndex].style.borderColor = 'white';
            // 颜色重置方法
            function resetColor() {  
              for(let i = 0;i<carouselBottomItem.length;i++)
                carouselBottomItem[i].style.borderColor = 'black';
            }  
            // 切换图片方法
            function switchImage(index) {  
              resetColor();
              currentIndex = index;  
              carouselBottomItem[index].style.borderColor = 'white';
              const xx = -currentIndex * 500
              carouselImages.style.transform = 'translateX('+xx+'px)';
            }  
            carouselPrevButton.addEventListener("click", () => {  
              poin = true;
              currentIndex--;  
              if (currentIndex < 0) {  
                currentIndex = imagesCount - 1; } switchImage(currentIndex);
            });  
            carouselNextButton.addEventListener("click", () => {  
              poin = true;
              currentIndex++;  
              if (currentIndex >= imagesCount) {  
                currentIndex = 0;   
              }  
              switchImage(currentIndex);}); 
            var timer = window.setInterval(function(){
              if(!poin){
                currentIndex++;  
                if (currentIndex >= imagesCount) {currentIndex = 0; } switchImage(currentIndex);  
              }else{poin = false;}
            },this.attributes.cirTime.value);
            sessionStorage.setItem(this.attributes.id.value,timer);
          }
        },
        init() {  
          let that = this;
          that.on('change:cirTime', function() {
              that.get('attributes').cirTime = that.attributes.cirTime
              // 回调script
              that.trigger("change:script");
          });  
          that.on('change:width', function() {
            that.get('attributes').width = that.attributes.width
            // 回调script
            that.trigger("change:script");
          }); 
          that.on('change:height', function() {
              that.get('attributes').height = that.attributes.height
              // 回调script
              that.trigger("change:script");
          }); 
        }, 
        removed() {
        },
      },
      view: {
        init() {
        },
        onRender({ el, model }) {
          // 监听外部拖拽传入的组件事件，暂时不行
          // model.on('component:add', (component, target) => {  
          //   if (target) {  
          //     console.log('组件', component.getType(), '被拖放到了组件', target.getType(), '内部');  
          //   }  
          // });
          model.getChildAt(0).getChildAt(0).forEachChild(child => {
            child.on('component:clone', function(originalModel, cloneModel) {
              if(model.getChildAt(0).getChildAt(0).get('components').length==6)return;
              model.trigger("change:script"); 
           })
           child.on('component:remove:before', function(model1, removeFn, options) {
            if(model.getChildAt(0).getChildAt(0).get('components').length==2){
              options.abort = true;
              return;
            }
                model.trigger("change:script"); 
            })
          })
        },
      },
    })

    // 注册组件
    editor.BlockManager.add('addCir-picture', {
        label: '轮播图图片(水平)',
        category: '图片类',
        content: {
          type:'addCirPicture',
        },
    });
};